package com.forum.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.forum.mapper.*;
import com.forum.pojo.*;
import com.forum.pojo.vo.*;
import com.forum.result.Result;
import com.forum.service.UserMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.jws.soap.SOAPBinding;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *
 */
@Service
public class UserMessageServiceImpl extends ServiceImpl<UserMessageMapper, UserMessage>
        implements UserMessageService {
    @Autowired
    private ForumArticleMapper forumArticleMapper;
    @Autowired
    private ForumCommentMapper forumCommentMapper;
    @Autowired
    private LikeRecordMapper likeRecordMapper;
    @Autowired
    private UserMessageMapper userMessageMapper;
    @Autowired
    private FriendsRelaMapper friendsRelaMapper;
    @Autowired
    private StudentInfoMapper studentInfoMapper;
    @Autowired
    private TeacherInfoMapper teacherInfoMapper;
    /**
     * 获取点赞过的文章
     *
     * @param userId
     * @return
     */
    @Override
    public List<LikeArticleVo> getLikeArticle(Long userId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("op_type", 0);
        queryWrapper.eq("user_id", userId);
        queryWrapper.select("object_id");
        List<LikeRecord> list = likeRecordMapper.selectList(queryWrapper);
        List<LikeArticleVo> likeArticleDetail = getLikeArticleDetail(list);
        return likeArticleDetail;
    }

    /**
     * 获取点赞过的文章并打包
     *
     * @param list
     * @return
     */
    private List<LikeArticleVo> getLikeArticleDetail(List<LikeRecord> list) {
        List<LikeArticleVo> result = new ArrayList<LikeArticleVo>();
        for (LikeRecord listItem : list) {
            ForumArticle forumArticle = forumArticleMapper.selectByArticleId(listItem.getObjectId());
            LikeArticleVo likeArticleVo = new LikeArticleVo();
            likeArticleVo.setArticleId(forumArticle.getArticleId());
            likeArticleVo.setAuthor(forumArticle.getNickName());
            likeArticleVo.setAvatarUrl(forumArticleMapper.findAvartarUrlByUserId(forumArticle.getUserId()));
            likeArticleVo.setPostTime(forumArticle.getPostTime());
            likeArticleVo.setTag(forumArticle.getTag());
            likeArticleVo.setSummary(forumArticle.getSummary());
            likeArticleVo.setTitle(forumArticle.getTitle());
            likeArticleVo.setCommentCount(forumArticle.getCommentCount());
            likeArticleVo.setGoodCount(forumArticle.getGoodCount());
            likeArticleVo.setReadCount(forumArticle.getReadCount());
            likeArticleVo.setAuthorIdentity(forumArticleMapper.selectIdentity(forumArticle.getUserId()));
            result.add(likeArticleVo);
        }
        return result;
    }

    /**
     * 获取点赞过的评论
     *
     * @param userId
     * @return
     */
    @Override
    public List<LikeCommentVo> getLikeComment(Long userId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("op_type", 1);
        queryWrapper.eq("user_id", userId);
        List<LikeRecord> list = likeRecordMapper.selectList(queryWrapper);
        List<LikeCommentVo> likeCommentDetail = getLikeCommentDetail(list);
        return likeCommentDetail;
    }

    /**
     * 获取点赞过的评论并打包
     *
     * @param list
     * @return
     */
    private List<LikeCommentVo> getLikeCommentDetail(List<LikeRecord> list) {
        List<LikeCommentVo> result = new ArrayList<LikeCommentVo>();
        for (LikeRecord listItem : list) {
            ForumComment forumComment = forumCommentMapper.selectByCommentId(Integer.valueOf(listItem.getObjectId()));
            LikeCommentVo likeCommentVo = new LikeCommentVo();
            ForumArticle forumArticle = forumArticleMapper.selectByArticleId(forumComment.getArticleId());
            likeCommentVo.setAuthor(forumComment.getNickName());
            likeCommentVo.setArticleId(forumComment.getArticleId());
            likeCommentVo.setAuthorIdentity(forumArticleMapper.selectIdentity(forumArticle.getUserId()));
            likeCommentVo.setAvatarUrl(forumArticleMapper.findAvartarUrlByUserId(forumComment.getUserId()));
            likeCommentVo.setGoodCount(forumComment.getGoodCount());
            likeCommentVo.setSummary(forumArticle.getSummary());
            likeCommentVo.setTitle(forumArticle.getTitle());
            likeCommentVo.setPostTime(forumComment.getPostTime());
            likeCommentVo.setContext(forumComment.getContent());
            result.add(likeCommentVo);
        }
        return result;
    }

    /**
     * 获取别人点赞我的帖子信息
     *
     * @param userId
     * @return
     */
    @Override
    public List<LikeArticleVo> getArticleLikeMessage(Long userId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("message_type", 2);
        queryWrapper.eq("received_user_id", userId);
        List<UserMessage> list = userMessageMapper.selectList(queryWrapper);
        List<LikeArticleVo> articleLikeMessageDetail = getArticleLikeMessageDetail(list);
        return articleLikeMessageDetail;
    }

    /**
     * 获取帖子点赞信息并打包
     *
     * @param list
     * @return
     */
    private List<LikeArticleVo> getArticleLikeMessageDetail(List<UserMessage> list) {
        List<LikeArticleVo> result = new ArrayList<LikeArticleVo>();
        for (UserMessage listItem : list) {
            LikeArticleVo likeArticleVo = new LikeArticleVo();
            String articleId = listItem.getArticleId();
            ForumArticle forumArticle = forumArticleMapper.selectByArticleId(articleId);
            likeArticleVo.setArticleId(articleId);
            likeArticleVo.setAuthor(listItem.getSendNickName());
            likeArticleVo.setTitle(listItem.getArticleTitle());
            likeArticleVo.setAvatarUrl(forumArticleMapper.findAvartarUrlByUserId(listItem.getSendUserId()));
            likeArticleVo.setPostTime(listItem.getCreateTime());
            likeArticleVo.setAuthorIdentity(forumArticleMapper.selectIdentity(listItem.getReceivedUserId()));
            likeArticleVo.setAuthorIdentity(forumArticleMapper.selectIdentity(listItem.getSendUserId()));
            result.add(likeArticleVo);
        }
        return result;

    }

    /**
     * 获取别人点赞我的评论信息
     *
     * @param userId
     * @return
     */
    @Override
    public List<LikeCommentVo> getCommentLikeMessage(Long userId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("message_type", 3);
        queryWrapper.eq("received_user_id", userId);
        List<UserMessage> list = userMessageMapper.selectList(queryWrapper);
        List<LikeCommentVo> commentLikeMessageDetail = getCommentLikeMessageDetail(list);
        return commentLikeMessageDetail;
    }

    /**
     * 获取评论点赞信息具体内容并打包
     *
     * @param list
     * @return
     */
    private List<LikeCommentVo> getCommentLikeMessageDetail(List<UserMessage> list) {
        List<LikeCommentVo> result = new ArrayList<>();
        for (UserMessage listItem : list) {
            LikeCommentVo likeCommentVo = new LikeCommentVo();
            ForumComment forumComment = forumCommentMapper.selectByCommentId(listItem.getCommentId());
            likeCommentVo.setArticleId(forumComment.getArticleId());
            likeCommentVo.setPostTime(listItem.getCreateTime());
            likeCommentVo.setContext(forumComment.getContent());
            likeCommentVo.setAuthor(listItem.getSendNickName());
            likeCommentVo.setAvatarUrl(forumArticleMapper.findAvartarUrlByUserId(listItem.getSendUserId()));
            likeCommentVo.setAuthorIdentity(forumArticleMapper.selectIdentity(listItem.getSendUserId()));
            result.add(likeCommentVo);
        }
        return result;
    }

    /**
     * 获取好友申请添加信息
     *
     * @param userId
     * @return
     */
    @Override
    public List<FriendMessageVo> getFriendMessage(Long userId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("message_type", 4);
        queryWrapper.eq("received_user_id", userId);
        queryWrapper.eq("status",0);
        List<UserMessage> list = userMessageMapper.selectList(queryWrapper);
        List<FriendMessageVo> result = getFriendMessageDetail(list);
        return result;
    }

    private List<FriendMessageVo> getFriendMessageDetail(List<UserMessage> list) {
        List<FriendMessageVo> friendMessageVos = new ArrayList<>();
        for (UserMessage listItem : list) {
            FriendMessageVo friendMessageVo = new FriendMessageVo();
            Long sendUserId = listItem.getSendUserId();
            friendMessageVo.setArticleCount(getUserArticleCount(sendUserId));
            friendMessageVo.setGoodCount(getUserLikeCount(sendUserId));
            friendMessageVo.setCommentCount(getUserCommentCount(sendUserId));
            friendMessageVo.setUserId(sendUserId);
            friendMessageVo.setNickName(forumArticleMapper.findNickNameByUserId(sendUserId));
            friendMessageVo.setAvatarUrl(forumArticleMapper.findAvartarUrlByUserId(sendUserId));
            friendMessageVo.setSignature(getUserSignature(sendUserId));
            friendMessageVo.setIdentity(forumArticleMapper.selectIdentity(sendUserId));
            friendMessageVos.add(friendMessageVo);
        }
        return friendMessageVos;
    }

    /**
     * 获取个性签名
     *
     * @param userId
     * @return
     */
    private String getUserSignature(Long userId) {
        return userMessageMapper.getUserSignature(userId);
    }

    /**
     * 获取评论的数量
     *
     * @param userId
     * @return
     */
    private Integer getUserCommentCount(Long userId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        return forumCommentMapper.selectCount(queryWrapper);
    }

    /**
     * 获取好友点赞过的数量
     *
     * @param userId
     * @return
     */
    private Integer getUserLikeCount(Long userId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        return likeRecordMapper.selectCount(queryWrapper);
    }

    /**
     * 获取好友发布的贴子
     *
     * @param userId
     * @return
     */
    private Integer getUserArticleCount(Long userId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        return forumArticleMapper.selectCount(queryWrapper);
    }

    /**
     * 获取评论消息
     *
     * @param userId
     * @return
     */
    @Override
    public List<LikeCommentVo> getCommentMessage(Long userId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("message_type", 1);
        queryWrapper.eq("received_user_id", userId);
        List list = userMessageMapper.selectList(queryWrapper);
        List<LikeCommentVo> commentMessageDetail = getCommentMessageDetail(list);
        return commentMessageDetail;
    }

    private List<LikeCommentVo> getCommentMessageDetail(List<UserMessage> list) {
        ArrayList<LikeCommentVo> likeCommentVos = new ArrayList<>();
        for (UserMessage listItem : list) {
            LikeCommentVo likeCommentVo = new LikeCommentVo();
            ForumArticle forumArticle = forumArticleMapper.selectByArticleId(listItem.getArticleId());
            likeCommentVo.setArticleId(listItem.getArticleId());
            likeCommentVo.setTitle(listItem.getArticleTitle());
            likeCommentVo.setSummary(forumArticle.getSummary());
            likeCommentVo.setAvatarUrl(forumArticleMapper.findAvartarUrlByUserId(listItem.getSendUserId()));
            ForumComment forumComment = forumCommentMapper.selectByTimeAndContent(listItem.getCreateTime(), listItem.getMessageContent());
            if(forumComment==null){
                continue;
            }
            likeCommentVo.setGoodCount(forumComment.getGoodCount());
            likeCommentVo.setPostTime(forumComment.getPostTime());
            likeCommentVo.setAuthorIdentity(forumArticleMapper.selectIdentity(listItem.getSendUserId()));
            likeCommentVo.setContext(listItem.getMessageContent());
            likeCommentVo.setAuthor(listItem.getSendNickName());
            likeCommentVos.add(likeCommentVo);
        }
        return likeCommentVos;
    }

    @Override
    public boolean HandleAddFriend(Long userId, Long friendId, Integer addType) {
        if (addType == 0) {
            return agree(userId, friendId);
        } else {
            return refuse(userId, friendId);
        }
    }

    private boolean refuse(Long userId, Long friendId) {
        return userMessageMapper.updateState(userId, friendId);
    }

    @Transactional(rollbackFor = {Exception.class}, readOnly = false)
    boolean agree(Long userId, Long friendId) {
        userMessageMapper.updateState(userId, friendId);
        FriendsRela friendsRela = new FriendsRela();
        friendsRela.setUserId(userId);
        friendsRela.setFriendId(friendId);
        friendsRelaMapper.insert(friendsRela);
        return true;
    }

    @Override
    public boolean AddFriendRequest(Long userId, Long friendId) {
        UserMessage userMessage = new UserMessage();
        userMessage.setMessageType(4);
        userMessage.setReceivedUserId(friendId);
        userMessage.setSendUserId(userId);
        userMessage.setSendNickName(forumArticleMapper.findNickNameByUserId(userId));
        userMessage.setCreateTime(new Date());
        if (userMessageMapper.insert(userMessage) == 1)
            return true;
        return false;
    }

    @Override
    public List<FriendMessageVo> getMyFriend(Long userId) {
        List myFriend = friendsRelaMapper.getMyFriend(userId);
        List<FriendMessageVo> myFriendMessageDetail = getMyFriendMessageDetail(myFriend);
        return myFriendMessageDetail;
    }

    private List<FriendMessageVo> getMyFriendMessageDetail(List list) {
        List<FriendMessageVo> friendMessageVos = new ArrayList<>();
        for (Object listItem : list) {
            FriendMessageVo friendMessageVo = new FriendMessageVo();
            Long sendUserId = (Long) listItem;
            friendMessageVo.setArticleCount(getUserArticleCount(sendUserId));
            friendMessageVo.setGoodCount(getUserLikeCount(sendUserId));
            friendMessageVo.setCommentCount(getUserCommentCount(sendUserId));
            friendMessageVo.setUserId(sendUserId);
            friendMessageVo.setNickName(forumArticleMapper.findNickNameByUserId(sendUserId));
            friendMessageVo.setAvatarUrl(forumArticleMapper.findAvartarUrlByUserId(sendUserId));
            friendMessageVo.setSignature(getUserSignature(sendUserId));
            friendMessageVos.add(friendMessageVo);
        }
        return friendMessageVos;
    }

    @Override
    public boolean deleteFriend(Long userId, Long friendId) {
        userMessageMapper.deleteFriend(userId, friendId);
        userMessageMapper.deleteFriend(friendId, userId);
        return true;
    }

    @Override
    public List<ChatVo> getChat(Long userId, Long friendId) {
        QueryWrapper<UserMessage> userMessageQueryWrapper = new QueryWrapper<>();
        userMessageQueryWrapper.eq("received_user_id", userId);
        userMessageQueryWrapper.eq("send_user_id", friendId);
        List<UserMessage> userMessages = userMessageMapper.selectList(userMessageQueryWrapper);
        for (UserMessage listItem : userMessages) {
            listItem.setStatus(1);
            userMessageMapper.updateById(listItem);
        }
        List<UserMessage> chats = userMessageMapper.getChat(userId, friendId);
        List<ChatVo> list=new ArrayList<>();
        for (UserMessage userMessage:chats) {
            ChatVo chatVo=new ChatVo();
            chatVo.setUserMessage(userMessage);
            QueryWrapper queryWrapper1 =new QueryWrapper();
            queryWrapper1.eq("studentId",userMessage.getSendUserId());
            QueryWrapper queryWrapper2=new QueryWrapper();
            queryWrapper2.eq("teacherId",userMessage.getSendUserId());

            StudentInfo studentInfo = studentInfoMapper.selectOne(queryWrapper1);
            TeacherInfo teacherInfo = teacherInfoMapper.selectOne(queryWrapper2);
            if(studentInfo!=null){
                chatVo.setAvartUrl(studentInfo.getAvartarurl());
            }else if(teacherInfo!=null){
                chatVo.setAvartUrl(teacherInfo.getAvartarurl());
            }
            list.add(chatVo);
        }
        return list;
    }

    @Override
    public boolean sendMessage(Long userId, Long friendId, String content) {
        QueryWrapper<UserMessage> userMessageQueryWrapper = new QueryWrapper<>();
        userMessageQueryWrapper.eq("send_user_id", userId);
        userMessageQueryWrapper.eq("received_user_id", friendId);
        Integer count1 = userMessageMapper.selectCount(userMessageQueryWrapper);
        Integer count2 = friendsRelaMapper.findRela(userId, friendId);
        if (count1 == 3 && count2 == 0) {
            return false;
        }
        UserMessage userMessage = new UserMessage();
        userMessage.setSendUserId(userId);
        userMessage.setSendNickName(forumArticleMapper.findNickNameByUserId(userId));
        userMessage.setReceivedUserId(friendId);
        userMessage.setCreateTime(new Date());
        userMessage.setStatus(0);
        userMessage.setMessageContent(content);
        userMessage.setMessageType(0);
        if (userMessageMapper.insert(userMessage) == 1)
            return true;
        return false;
    }

    @Override
    public Result getChatList(Long userId) {
        List<ChatListVo> chatList = userMessageMapper.getChatList(userId);
        for (ChatListVo chatListVo:chatList) {
            QueryWrapper queryWrapper1 =new QueryWrapper();
            queryWrapper1.eq("studentId",chatListVo.getSendUserId());
            QueryWrapper queryWrapper2=new QueryWrapper();
            queryWrapper2.eq("teacherId",chatListVo.getSendUserId());
            StudentInfo studentInfo = studentInfoMapper.selectOne(queryWrapper1);
            TeacherInfo teacherInfo = teacherInfoMapper.selectOne(queryWrapper2);
            if(studentInfo!=null){
                chatListVo.setAvartUrl(studentInfo.getAvartarurl());
            }else if(teacherInfo!=null){
                chatListVo.setAvartUrl(teacherInfo.getAvartarurl());
            }
        }
        return Result.ok(chatList);
    }

    @Override
    public Integer getMessageCount(Long userId, Integer type) {
        Integer result;
        QueryWrapper<UserMessage> userMessageQueryWrapper = new QueryWrapper<>();
        userMessageQueryWrapper.eq("received_user_id", userId);
        userMessageQueryWrapper.eq("status",0);
        if (type == 0)
            userMessageQueryWrapper.eq("message_type", 0);
        if (type == 1)
            userMessageQueryWrapper.eq("message_type", 1);
        if (type == 2)
            userMessageQueryWrapper.eq("message_type", 2).or().eq("message_type",3);
        if (type == 4)
            userMessageQueryWrapper.eq("message_type", 4);
        result = userMessageMapper.selectCount(userMessageQueryWrapper);
        return result;
    }

    @Override
    public boolean judgeFriend(Long userId, Long friendId) {
        if(friendsRelaMapper.findRela(userId,friendId)!=0)
            return true;
        return false;
    }
}
